// src/util.js
import Web3 from "web3";
import ballotJson from './contract/ballot.json';

// 合约地址
const ballotAddr = "0xa43A01eB23879E7432E49ED003a61eD6175337f2";

const useWeb3 = () => {
  // 确保在浏览器环境下获取 MetaMask 提供的 window.ethereum
  if (typeof window.ethereum === 'undefined') {
    throw new Error('MetaMask is not installed');
  }

  // 初始化 Web3 实例，使用 MetaMask 提供的 ethereum 对象
  const web3 = new Web3(window.ethereum);

  // 创建合约实例
  const ballotSm = new web3.eth.Contract(ballotJson.abi, ballotAddr);

  // 获取当前连接的账户
  const getAccount = async () => {
    try {
      // 请求 MetaMask 获取账户
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });

      // 返回第一个账户地址
      return accounts[0];
    } catch (error) {
      console.error("Error getting account:", error);
      throw new Error("User rejected the request or there was an error");
    }
  };

  return {
    web3,
    ballotSm,
    ballotAddr,
    getAccount
  };
};

export default useWeb3;
